package edu.mbb.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import edu.mbb.basepackage.GetPaceOverClass;
import edu.mbb.basepackage.GetXMLConfiguration;
import edu.mbb.ioc.BeanFactory;
import edu.mbb.ioc.DIClass;

public class ContextLoaderListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		ServletContext servletContext = arg0.getServletContext();
		// 取出对应的初始化参数
		String initParameter = servletContext.getInitParameter("contextPath");
		if (initParameter == null || initParameter.length() > 0) {
			initParameter = "classpath:application.properties";
		}
		// 加载配置文件开始
		String[] split = initParameter.split(":");
		// 读到对应的配置文件
		String path = split[1];
		String basePackage = null;
		String xmlPath = null;
		InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(path);
		Properties pro = new Properties();
		try {
			pro.load(resourceAsStream);
			// 得到扫描包的路径
			basePackage = pro.getProperty("scanPackage");
			xmlPath = pro.getProperty("xmlPath");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("配置文件路径不存在");
			e.printStackTrace();
		}
		// 开始解析对应的注解和ioc解析
		// 开始 扫包开始 把注解全扫出来 ioc 注入完成
		GetPaceOverClass.getAllPackOverClass(BeanFactory.getIOC(), basePackage);
		// 进行依赖注入 扫描注解 autowite
		DIClass.Di();
		// 初始化 mybatis配置文件信息
		// 解析xml配置文件 进行 开始解析
		// xmlPath
		GetXMLConfiguration.init(xmlPath);
		/// EmpMapper employeeMapper = (EmpMapper)
		/// BeanFactory.getIOC().get("EmpMapper");
		// Emp findById = employeeMapper.findById("100");
		// System.out.println(findById);
	}

}
